/**
 * 数字看板
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cass from 'classnames';
import { Icon } from 'antd';
import _ from 'lodash';
import { isSuccess } from '../../configs/error';
// import { widgetApi, widgetServices } from '../../services/analysis';
import css from './style.less';

// const keys = Object.keys(widgetApi);

class DigitalBoard extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			data: 0,
			display: '获取中',
			queryData: props.queryData
		};
	}

	componentWillMount() {
		this.query();
	}

	componentWillReceiveProps(nextProps) {
		this.setState({ queryData: nextProps.queryData });
	}

	componentDidUpdate(prevProps, prevState) {
		if (!_.isEqual(prevState.queryData, this.state.queryData)) {
			this.query();
		}
	}

	async query() {
		const { uri, needQueryKeys, name } = this.props;
		const { query } = this.props;
		const { queryData } = this.state;
		// if (!query) {
		// 	const key = keys.find(k => widgetApi[k] === uri);
		// 	query = widgetServices[key];
		// }

		if (needQueryKeys && needQueryKeys.length && queryData) {
			if (needQueryKeys.some(k => !queryData[k] && queryData[k] !== 0)) return;
		}
		// if (!queryData || !queryData.productId) queryData = undefined;
		const res = await query(queryData);
		if (isSuccess(res)) {
			this.setState({
				data: res.data,
				display: res.display || name
			});
		} else {
			throw res;
		}
	}

	render() {
		const { dataKey, type, icon } = this.props;
		const { data, display } = this.state;
		const d = (typeof dataKey === 'function' ? dataKey(data) : data) || 0;
		const num = typeof d === 'object' ? d.data : d;
		const increase = typeof d === 'object' ? d.odd : null;
		return (
			<div className={cass('digitalBoard', css.main, type || icon)}>
				<i className="digitalBoard-img" />
				<div>
					<span className={cass(css.title, 'digitalBoard-title')}>{display}</span>
					<div className={cass(css.text, 'digitalBoard-text')}>
						{num}
						{
							increase !== null ?
								<span className={cass(css.span, 'digitalBoard-span')}>
									<Icon type={increase < 0 ? 'arrow-down' : 'arrow-up'} />
									{Math.abs(increase)}
								</span> : null
						}
					</div>
				</div>
			</div>
		);
	}
}

DigitalBoard.propTypes = {
	query: PropTypes.func, // 请求数据方法
	name: PropTypes.string, // 标题
	dataKey: PropTypes.string // 数据的key
};

export default DigitalBoard;
